#!/bin/sh
# Windows Install
# By Sergey_Galan (Serhii Halaniuk)
# Copyright (c) 2024, Sergey_Galan (Serhii Halaniuk). All Right Reserved
# Credit: Wimlib, ntfs-3g-utils, Platypus


Password()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
echo "STOP! Incorrect password!"
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Неверный пароль!"\r"Введите пароль администратора.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Невірний пароль!"\r"Введіть пароль адміністратора.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"Incorrect password!"\r"Enter admin password.""
exit 1
}


imgTest()
{
echo "STOP! The image doesn\'\t exist!"
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Образ не существует!"\r"Перетяните на окно программы образ с расширением wim или esd.""
    exit 1
fi
if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Образ не існує!"\r"Перетягніть на вікно програми образ із розширенням wim або esd.""
    exit 1
fi
echo "Info:\r\r\r\r\r\r\r"The image doesn\'\t exist!"\r"Drag an image with a wim or esd extension onto the program window.""
exit 1
}


Time()
{
finishTime=$(date -u "+%s")
processedTime=$(expr $finishTime - $startTime)
if [[ $processedTime -gt 3599 ]]; then
    processedTime=$(printf "%dh%dm%ds\n" $((processedTime/3600%3600)) $((processedTime/60%60)) $((processedTime%60)))
elif [[ $processedTime -gt 59 ]]; then
    processedTime=$(printf "%dm%ds\n" $((processedTime/60%60)) $((processedTime%60)))
 else
    processedTime=$(printf "%ds\n" $((processedTime)))
fi
}


Finish()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`
if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Процесс завершён."\r"Времени потрачено: $processedTime""
elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Процес завершено."\r"Часу витрачено: $processedTime""
else
    echo "Info:\r\r\r\r\r\r\r"The process is completed."\r"Time is spent: $processedTime""
fi
}


Compression()
{
echo "TextPosition:Center"
if [[ ! "$(./tools/bin/wimlib-imagex info "$file")" ]]; then
    sleep 0.5
    echo "Info:\r\r\r\r\r\r\r\rImage... Error"
    echo
    echo "STOP! Image... Error"
    exit 1
fi

tfile="${file##*/}"
ext="${file##*.}"
if [[ `echo "wim" 2>&1 | grep -i $ext` ]]; then
    press="--check --recompress --compress=LZMS:100 --solid"
    rpress="WIM -> ESD"
elif [[ `echo "esd" 2>&1 | grep -i $ext` ]]; then
    press="--check --recompress --compress=LZX:50"
    rpress="ESD -> WIM"
else
    imgTest
fi

passWinInstal=Mac-"$(ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/' | cut -f2 -d"=" | tr -d '" ' | cut -f5-5 -d '-' | tr -d - | rev)"
mypassword=$(security find-generic-password -wl ${passWinInstal} 2>/dev/null)
echo "$mypassword" | sudo -S echo "Ok" || Password
sudo -S ./Tools/bin/wimlib-imagex optimize "$file" $press 2>&1 |
while IFS= read -d $'\r' -r p; do
  echo "$p"

  if [[ `echo "$p" | grep -w "Verifying integrity"` ]] || [[ `echo "$p" | grep -w "Calculating integrity"` ]]; then
      inst=${p/(*/}
      inst=$(echo $inst | sed -e s/' integrity table'//g)
      inst=$(echo $inst | sed -e s!" of ""\"$file"\"!!g)
      #pr=0
  else
      inst=${p/(*/}
      inst=$(echo $inst | sed -e s!"\"$file"\"!!g)
      pr=${p/*(/}
      pr=${pr/"%"*}
  fi

  echo "Media:"$inst""
  echo "Info:\r\r\r\r\r\r\r"$tfile"\r"Recompress $rpress"\r"$remainderTime""

  if [[ "$pr" -gt "0" ]]; then
      echo "Progress:""$pr""% "
  else
      echo "Progress:""0""% "
  fi 2>/dev/null

  tempTime=$(date -u "+%s")
  if [[ "$prOld" -lt "$pr" ]] && [[ "$tempTimeOld" -lt "$tempTime" ]]; then
      prRem=$(expr 100 - $pr)
      processedTime=$(expr $tempTime - $tempTimeOld)
      remTime=$(expr $prRem \* $processedTime)

      if [[ $remTimeOld -gt "0" ]]; then
          remTime=$(expr $remTime + $remTimeOld)
          remTime=$(expr $remTime / 2)
      fi
      remTimeOld=$remTime

      if [[ $remTime -gt 3599 ]]; then
          remainderTime=$(printf "%dh%dm\n" $((remTime/3600%3600)) $((remTime/60%60)))

      elif [[ $remTime -gt 59 ]]; then
            remainderTime=$(printf "%dm%ds\n" $((remTime/60%60)) $((remTime%60)))

      elif [[ $remTime -gt "0" ]]; then
            remainderTime=$(printf "%ds\n" $((remTime)))
      fi
      tempTimeOld="$tempTime"
  fi &> /dev/null
  prOld="$pr"
done
ext="${file##*.}"
if [[ `echo "wim" 2>&1 | grep -i $ext` ]]; then
    fileNew="${file%.*}".esd
    mv "$file" "$fileNew"
elif [[ `echo "esd" 2>&1 | grep -i $ext` ]]; then
    fileNew="${file%.*}".wim
    mv "$file" "$fileNew"
fi
}


##################################################################################
###### Start script execution routine ############################################
##################################################################################


WindowsInstallPlist="$HOME/Library/Preferences/org.SerhiiHalan.SettingsWindowsInstall.plist" &> /dev/null
Mode="$(defaults read $WindowsInstallPlist PMode)"

if [[ $Mode = "WIM   <->   ESD" ]]; then
    echo "################### START Compression ####################"
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Info: "
    for file in "$@"; do
    startTime=$(date -u "+%s")
    echo "Progress:""0""% "
    Compression
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null &
    ttfile="${fileNew##*/}"
    echo "Media:"$ttfile" ... Complete"
    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "NOTIFICATION:Complete: "$rpress" "$ttfile"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    sleep 1
    #open /Volumes/
    done
    echo "########################### End ###########################"
    exit
fi


if [[ -f "$1" ]]; then
    echo "############### Search for Windows editions ################"
    echo "Media: "
    echo "Info: "
    echo "Progress:""0""% "
    echo "TextPosition:Left"

    ext="${1##*.}"
    if [[ `echo "wim esd" 2>&1 | grep -i $ext` ]]; then
        sleep 0.5
        echo "Info: \r"$(./tools/bin/wimlib-imagex info "$1" | sed -e s/'Display Name:'//g | sed -e s/'Product Name:'//g | grep 'Index:\|Name:\|Flags:\|System Root:' | grep -v 'Boot' | tr -s ' ' ' ' | sed -e s/'Name:'//g | sed -e s/'System Root:'//g | sed -e s/'Flags:'//g | sed -e s/Index/']Index'/g | tr -s ']' '\r')""
        if [[ ! "$(./tools/bin/wimlib-imagex info "$1")" ]]; then
            echo "TextPosition:Center"
            echo "Info:\r\r\r\r\r\r\r\rImage... Error"
            echo
            echo "STOP! Search for Windows editions... Error"
            exit 1
        fi
  elif [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
        for disk in /Volumes/*/sources/install.*; do
            if [[ -f "$disk" ]]; then
                disk="${disk///sources*}"
                diskutil eject "$disk"
            fi
        done
        sleep 0.5
        hdiutil mount "$1"
        echo "Info: \r"$(./tools/bin/wimlib-imagex info /V*/*/sources/install.* | grep 'Index:\|Display Name:' | grep -v 'Boot' | tr -s ' ' ' ' | sed -e s/'Display Name'/'Edition'/g | sed -e s/Index/']Index'/g | tr -s ']' '\r')""
        if [[ ! "$(./tools/bin/wimlib-imagex info /V*/*/sources/install.*)" ]]; then
            echo "TextPosition:Center"
            echo "Info:\r\r\r\r\r\r\r\rImage... Error"
            echo
            echo "STOP! Search for Windows editions... Error"
            exit 1
        fi
        for disk in /Volumes/*/sources/install.*; do
            if [[ -f "$disk" ]]; then
                disk="${disk///sources*}"
                diskutil eject "$disk"
            fi
        done
    fi
    /usr/libexec/PlistBuddy -c "Add :ImageWIM string " "$WindowsInstallPlist"
    /usr/libexec/PlistBuddy -c "Set :ImageWIM $1" "$WindowsInstallPlist"
fi
echo "########################### End ###########################"
exit
